/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import binding.carts.Order;
import binding.orderdetails.OrderDetails;
import binding.orders.Orders;
import binding.userdetails.UserDetailType;
import core.DBEntities;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import utils.DefaultErrorHandler;
import utils.XmlUtils;
import utils.XmlValidate;

/**
 *
 * @author VanVT60365
 */
public class CheckOutController extends HttpServlet {

    private final String pageCheckoutSuccess = "/client/checkoutsuccessful.jsp";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            String webPath = getServletContext().getRealPath("/");
            String xsdShopcarts = webPath + "WEB-INF/classes/schemas/shopcarts.xsd";
            String xmlUsers = webPath + "WEB-INF/XmlDoc/Users.xml";
            if (action.equals("CHECK_OUT")) {
                HttpSession session = request.getSession();
                Object sCart = session.getAttribute("CART_DOC");
                Object uid = session.getAttribute("USER_ID");
                //Object uDetail = session.getAttribute("USER_DETAIL_ID");
                if (sCart != null) {
                    String cart = (String) sCart;
                    Node doc = XmlUtils.parseDOMFromString(cart);

                    Node useridNode = XmlUtils.getOneNodeFromDom(doc, "//*[name()='UserId']");
                    useridNode.setTextContent(uid.toString());
//                    GregorianCalendar gDate = new GregorianCalendar();
//                    gDate.setTime(new Date());
//                    String date = DatatypeFactory.newInstance().newXMLGregorianCalendar(gDate).toXMLFormat();
//                    dateNode.setTextContent(date);

                    DefaultErrorHandler handler = new DefaultErrorHandler();
                    XmlValidate.validate(xsdShopcarts, new DOMSource(doc), handler);
                    if (handler.isError()) {
                        String res = "<?xml version='1.0' encoding='UTF-8'?>";
                        res += "<error>" + handler.getErrorMessage() + "</error>";
                        response.setContentType("text/xml");
                        out.write(res);
                    } else {
                        Source source = new DOMSource(doc);
                        Object orderObj = XmlUtils.unMarshalXml(xsdShopcarts, source, Order.class);
                        if (orderObj instanceof Order) {
                            //int detailId = 0;
                            //UserDetailType udt = DBEntities.getUserDetailById(uid.toString());
//                            if (uDetail == null) {
//                                UserDetailType detail = new UserDetailType();
//                                detail.setAddress(request.getParameter("address"));
//                                detail.setAccommodationType("");
//                                detail.setDistrict(request.getParameter("district"));
//                                detail.setEmail(request.getParameter("email"));
//                                detail.setLastname(request.getParameter("lastname"));
//                                detail.setName(request.getParameter("name"));
//                                detail.setPhoneNum(request.getParameter("phonenum"));
//                                detail.setProvince(request.getParameter("province"));
//                                detail.setWard(request.getParameter("ward"));
//
//
//                                if (uId == null) {
//                                    //anonymous
//                                    detailId = DBEntities.insertUserDetail(detail);
//                                    UserDetails uDetails = DbEntities.getUserDetails();
//                                    XmlUtils.marshalXml(uDetails, webPath + "WEB-INF/XmlDoc/UserDetails.xml");
//                                } else {
//                                    Integer bUid = (Integer) uId;
//                                    Node domUsers = XmlUtils.parseDOM(xmlUsers);
//                                    Node detailIdNode = XmlUtils.getOneNodeFromDom(domUsers, "//*[name()='User'][*[name()='Id']='" + bUid.intValue() + "']/*[name()='UserDetailId']");
//                                    if (detailIdNode != null) {
//                                        detailId = CommonUtils.convertStringToInt(detailIdNode.getTextContent());
//                                    }
//                                }
//                            }else{
//                                Integer inter=(Integer)uDetail;
//                                if(inter!=null){
//                                    detailId=inter.intValue();
//                                }
//                            }

                            Order tempOrder = (Order) orderObj;
                            //tempOrder.setUserId(BigInteger.valueOf(Integer.parseInt(uid.toString())));
//                                tempOrder.setPaymentMethod(request.getParameter("payment"));
//                                tempOrder.setDeliveryTime(request.getParameter("delivery"));
//                                tempOrder.setNotes(request.getParameter("notes"));
//                                tempOrder.setStatus(request.getParameter(""));
//                                tempOrder.setIsActive(true);
                            int orderId = DBEntities.saveNewOrder(tempOrder);
                            String message = "";
                            if (orderId == 0) {
                                message = "<?xml version='1.0' encoding='UTF-8'?>";
                                message += "<error>" + "Checkout Error" + "</error>";

                            } else {
                                Orders listorders = DBEntities.getOrders();
                                if (listorders != null) {
                                    XmlUtils.marshalXml(listorders, webPath + "WEB-INF/XmlDoc/Orders.xml");
                                }
                                OrderDetails listod = DBEntities.getOrderDetails();
                                if (listod != null) {
                                    XmlUtils.marshalXml(listod, webPath + "WEB-INF/XmlDoc/OrderDetails.xml");
                                }
                                session.setAttribute("CART_DOC", null);
                                // session.setAttribute("USER_DETAIL_ID", detailId);

                                message = "<?xml version='1.0' encoding='UTF-8'?>";
                                message += "<redirect>" + getServletContext().getContextPath() + pageCheckoutSuccess + "?orderid=" + orderId + "</redirect>";
                            }
                            response.setContentType("text/xml");
                            out.write(message);
//                            if (detailId != 0) {
//                            }
                        }
                    }
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(CheckOutController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(CheckOutController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(CheckOutController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
